<script setup>

import {Coin, Moon, Sunny, Wallet} from "@element-plus/icons-vue";
import * as echarts from 'echarts';
import {onMounted, onUnmounted, ref} from "vue";
import {ElMessage} from "element-plus";

// location.reload();
// 控制抽屉
const drawer = ref(false)

// 充值或提现对话框
const dialogVisible = ref(false)

//充值或提现弹窗标题
const title = ref('')
//提现金额方法
const withdrawals = async () => {
    if (!validateInput()) {
        ElMessage.error('请输入正确的金额数,只能输入两位小数！')
        return;
    }
    // 如果输入有效，则执行提现操作
    const result = await withdrawalsService(input.value)
    ElMessage.success('提现成功')
    // 充值成功后刷新页面
    location.reload();
    dialogVisible.value = false;
}
//充值金额方法
const deposits = async () => {
    if (!validateInput()) {
        ElMessage.error('请输入正确的金额数,只能输入两位小数！')
        return;
    }
    // 如果输入有效，则执行提现操作
    const result = await depositsService(input.value)
    ElMessage.success('充值成功')
    // 充值成功后刷新页面
    location.reload();
    dialogVisible.value = false;

}
//提现或者充值的金额
const input = ref(0);
const validateInput = () => {
    if (!input.value) {
        return false;
    }
    const numericRegex = /^[0-9]+(\.[0-9]{1,2})?$/;//只能输入两位小数

    if (!numericRegex.test(input.value)) {
        return false;
    }
    // 金额是否大于0
    return parseFloat(input.value) > 0;
}
// 账单信息数据模型
const tableData = ref([
    {btime: ''},
    {btype: ''},
    {bamount: ''},
])

import {useUserInfoStore} from '@/store/user.js'
import {billListGetService, billSumGetService, getPOrderInfoService, withdrawalsService} from "@/api/bill";
import {depositsService} from "@/api/bill";
import {userInfoGetService} from "@/api/user";

const userInfoStore = useUserInfoStore();//获取个人信息（金额）
//获取个人信息
const getUserInfo = async () => {
    let result = await userInfoGetService();
    //存储pinia
    userInfoStore.info = result.data;
}
getUserInfo()
const billSum = ref({
    totalTodayRevenue: 0,//今日收入
    totalMonthRevenue: 0,//本月收入
    totalRevenue: 0//累计收入
})
//获取今日收入、本月收入、累计收入
const billSumGet = async () => {
    const result = await billSumGetService();

    billSum.value.totalTodayRevenue = result.data.totalTodayRevenue;
    billSum.value.totalMonthRevenue = result.data.totalMonthRevenue;
    billSum.value.totalRevenue = result.data.totalRevenue;
}
billSumGet()//获取收入数据

//获取账单信息
const getBillList = async () => {
    let result = await billListGetService();//获取折线图
   let res=await getPOrderInfoService();//获取饼状图
    tableData.value = result.data.map(bill => ({
        // 时间格式转换
        btime: new Date(bill.btime).toLocaleString('en-US', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            hour12: false
        }).replace(',', ''),
        //交易类型转换
        btype: getTypeLabel(bill.btype),
        // 交易金额
        bamount: bill.bamount
    }));
    // 获取最近7天的账单信息
    const endDate = new Date(); // 当前日期
    const startDate = new Date(endDate); // 开始日期为当前日期
    startDate.setDate(startDate.getDate() - 6); // 7天前的日期
    // 过滤出近7天的支出信息
    const recentPay = result.data.filter(bill => new Date(bill.btime) >= startDate && bill.btype === 0);

    // 调用函数渲染折线图
    renderLineChart_revenue(recentPay);
    // 调用函数渲染折线图
    renderLineChart_pie(res.data);
}
//图表渲染
const renderLineChart_revenue = (recentData) => {
    const currentDate = new Date();
    // 构建当前日期开始的最近7天日期数组
    const recentXAxisData = [];
    for (let i = 6; i >= 0; i--) {
        const date = new Date(currentDate);
        date.setDate(date.getDate() - i);
        const formattedDate = date.toISOString().slice(0, 10); // 格式化为 YYYY-MM-DD
        recentXAxisData.push(formattedDate);
    }

// 构建当前日期开始的最近7天支出数据数组，如果某天没有账单记录，则支出金额为0
    const recentSeriesData = recentXAxisData.map(date => {
        // 找到所有日期匹配的账单数组
        const matchingBills = recentData.filter(bill => bill.btime.slice(0, 10) === date);
        // 如果有匹配的账单
        if (matchingBills.length > 0) {
            // 使用 reduce 函数累加支出金额，并保留两位小数
            return matchingBills.reduce((acc, curr) => acc + curr.bamount, 0).toFixed(2);
        } else {
            return "0"; // 没有匹配的账单，支出金额为0
        }
    });


    // 使用 ECharts 初始化折线图实例
    const myChart1 = echarts.init(document.getElementById('pay'));
    myChart1.setOption({
        title: [
            {
                left: 'center',
                text: '近7天支出趋势图'
            }
        ],
        xAxis: {
            type: 'category',
            data: recentXAxisData,
            axisLabel: {
                formatter: function (value) {
                    // 只返回月份和天数
                    return value.slice(5);
                }
            }
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            data: recentSeriesData,
            type: 'line',
            symbol: 'none'
        }],
        lineStyle: {
            width: 3,  // 设置线宽
            color: {
                type: 'linear',  // 渐变类型为线性渐变
                x: 0,  // 渐变起始位置 x 坐标
                y: 0,  // 渐变起始位置 y 坐标
                x2: 0,  // 渐变结束位置 x 坐标
                y2: 1,  // 渐变起始位置 x 坐标
                colorStops: [{
                    offset: 0,  // 渐变起始位置，从 0 开始
                    color: '#E13b82'  // 渐变起始颜色
                }, {
                    offset: 1,  // 渐变结束位置，到 1 结束
                    color: 'lightblue'  // 渐变结束颜色
                }]
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: 'pink'
                }
            }
        }
    });
}
//饼图
const renderLineChart_pie=(data)=>{
    let myChart2 = echarts.init(document.getElementById("ratio"));
    //配置项
    myChart2.setOption({
        title: [
            {
                left: 'center',
                text: '商品购买量占比图'
            }
        ],
        legend: {
            orient: 'vertical',
            left: 'left',
            padding: 10
        },
        tooltip: {
            trigger: 'item'
        },
        series: [
            {
                name: 'Access From',
                type: 'pie',
                radius: '50%',
                data: data.map(item => ({
                    name: item.categoryName,
                    value: item.numb
                })),
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    });
}
//交易类型转换
const getTypeLabel = (type) => {
    switch (type) {
        case 0:
            return '支出';
        case 1:
            return '退款';
        case 2:
            return '充值';
        case 3:
            return '提现';
        default:
            return '';
    }
};
getBillList()
</script>
<template>
  <!--    //顶部的财务盒子-->
    <div class="wallet_box">
        <!--    上部分-->
        <div style="padding-top: 20px;padding-left: 100px;font-size: 17px">钱包余额</div>
        <div style="padding-left: 30px;margin-top: 5px;padding-bottom: 5px">
            <el-icon size="48px" style="vertical-align:middle">
                <Wallet/>
            </el-icon>
            <div style="display: inline-block;width: 600px;padding-left: 18px;"><span
                    style="font-size: 25px">￥{{ userInfoStore.info.pbalance }}</span></div>
            <el-button type="primary" class="el-button_revenue"
                       @click="dialogVisible = true;title='请输入充值金额';input=''">充值
            </el-button>
            <el-button type="warning" @click="dialogVisible = true;title='请输入提现金额';input=''">提现</el-button>
            <el-link :underline="false" @click="drawer = true"
                     style="color: white;width: 100px;height: 50px; padding-left: 40px;font-size: 18px">钱包记录
            </el-link>
        </div>

        <!--        交易记录的抽屉-->
        <el-drawer v-model="drawer" title="交易记录" :with-header="false" style="color:black;background-color: #cccccc"
                   :size="550">
            <el-table :data="tableData" :header-cell-style="{
            textAlign: 'center',
            height: '30px',}" :row-style="{height: '20px'}"
                      style="width: 100%;font-size: 16px; background-color: whitesmoke; border-left:pink  solid 3px;border-top: deeppink solid 2px;"
                      size="small"
                      height="560" stripe>
                <el-table-column prop="btime" align="center" label="日期" width="150"/>
                <el-table-column prop="btype" align="center" label="交易" width="160"/>
                <el-table-column prop="bamount" align="center" label="金额">
                    <template v-slot="scope">
                        <span :style="{ color: getAmountColor(scope.row.btype) }">
                             {{
                            (scope.row.btype === "支出") || (scope.row.btype === "提现") ? '-' : ((scope.row.btype === "充值") || (scope.row.btype === "退款") ? '+' : '')
                            }}
                            {{ scope.row.bamount }}
                        </span>
                    </template>
                </el-table-column>
            </el-table>
        </el-drawer>

        <!--   下部分 -->
        <div style="height: 100px;padding-top:35px;padding-left: 30px;color: #E8B5C3">
            <div class="revenue_small_box">
                <el-icon size="55px" class="money_icon">
                    <Sunny/>
                </el-icon>
                <span class="money_word">本日支出</span>
                <div class="money_numb">
                    ￥{{ billSum.totalTodayRevenue }}
                </div>
            </div>

            <div class="revenue_small_box">
                <el-icon size="55px" class="money_icon">
                    <Moon/>
                </el-icon>
                <span class="money_word">本月支出</span>
                <div class="money_numb">
                    ￥{{ billSum.totalMonthRevenue }}
                </div>
            </div>

            <div class="revenue_small_box">
                <el-icon size="55px" class="money_icon">
                    <Coin/>
                </el-icon>
                <span class="money_word">累计支出</span>
                <div class="money_numb">
                    ￥{{ billSum.totalRevenue }}
                </div>
            </div>
        </div>

    </div>
  <!--    饼状图-->
    <div id="ratio" style="margin-top:120px;margin-left:50px;display:inline-block;width: 46%;height: 300px;">
        饼状图
    </div>
    <div id="pay" style="margin-top:120px;margin-left:10px;display:inline-block;width: 46%;height: 300px;">
        折线图
    </div>

  <!--        提现金额输入框-->
    <el-dialog
            v-model="dialogVisible"
            :title="title"
            width="500"
            :before-close="handleClose"
    >
        <el-input v-model="input" style="width:350px" plain/>
        <template #footer>
            <div>
                <span class="dialog-footer">
            <el-button @click="dialogVisible = false;">取消</el-button>
            <el-button type="primary" @click="title==='请输入提现金额'?withdrawals():deposits ()"> 确认 </el-button>
        </span>
            </div>
        </template>
    </el-dialog>
</template>

<script>
export default {
    name: "FinancialManagement_P",
    methods: {
        getAmountColor(type) {
            switch (type) {
                case "支出": //支出
                case "提现": //提现
                    return 'black';
                case "退款": //收入
                case "充值": //充值
                    return 'orange';
                default:
                    return 'inherit';
            }
        }
    }
}
</script>

<style scoped>
.wallet_box {
    margin: 0 auto;
    margin-top: 1px;
    width: 650px;
    height: 70px;
    background-color: #E8B5C3;
    border-radius: 10px;
    color: white;
}

.el-button {
    background-color: white;
    /*color:deepskyblue;*/
    color: #FFC0CA;
    height: 30px;
    width: 60px;
    border: none;
}

.el-button_revenue:hover {
    background-color: #E13b82;
}

/*收入的三个小方块的总结*/
.revenue_small_box {
    height: 50px;
    width: 25%;
    display: inline-block;
    margin-left: 38px;

}

/*//金钱的数字*/
.money_numb {
    color: #E13b82;
    width: 200px;
    padding-left: 18px;
    vertical-align: middle;
    font-size: 16px;
}

/*描述金额的文字*/
.money_word {
    font-size: 13px;
    vertical-align: top;
    color: rgba(24, 24, 48, 0.59);
}

/*金额旁边的图标*/
.money_icon {
    float: left;
    vertical-align: middle;
    color: #E8B5C3
}

</style>
